package cn.learn.pay.wechat.util;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;


/**
 * 微信支付工具类
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2021年09月02日22:57
 */
@Slf4j
@UtilityClass
public class WeChatPayUtil {

    public static String weChatPayPost(String url, String contentMap, String mchId) {

        try (InputStream inputStream = WeChatPayUtil.class.getClassLoader().getResourceAsStream("")) {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(inputStream, mchId.toCharArray());

            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();
            // 只允许TLSv1协议
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext.getSocketFactory(),
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

            //创建基于证书的httpClient,后面要用到
            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (KeyStoreException e) {
            log.error("生成秘钥库异常：{}", e.getMessage());
        } catch (CertificateException e) {
            log.error("加载的证书有问题：{}", e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            log.error("加载的证书算法异常：{}", e.getMessage());
        } catch (IOException e) {
            log.error("加载证书流有问题：{}", e.getMessage());
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }


}
